var crcDB = null;

/*! Initialize the crcDB global variable. */
function initDB() {

    if (crcDB == null) {
        try {

            if (!window.openDatabase) {
                alert('not supported');
            } else {
                var shortName = 'crcInv1';
                var version = '1.0';
                var displayName = 'CRC Database';
                var maxSize = 1024 * 1024 * 5; // in bytes
                var myDB = openDatabase(shortName, version, displayName, maxSize);
                //alert("database created");
            }
        } catch (e) {
            // Error handling code goes here.
            if (e == INVALID_STATE_ERR) {
                // Version number mismatch.
                alert("Invalid database version.");
            } else {
                alert("Unknown error " + e + ".");
            }
            return;
        }

//        ExecuteQuery('Create Table Test1(ID integer);', myDB);
        crcDB = myDB;
    }

}

var errDBCallback = function (transaction, result, callback) {
    debugger;
    alert("SQL Error: " + result);
    console.log("SQL Error" + result);
}

/*This function is used to execute query*/
function ExecuteQuery(query, db) {
    try {
        console.log("Executeing query: " + query);
        //console.log(db);
        //console.log(db.transaction);
        db.transaction(
            function (transaction) {
                //console.log("In");
                transaction.executeSql(query, [], function (tx, e) { console.log("Sucess" + e) }, function (tx, e) { console.log("Fail: " + e) });
                //console.log("In Completed");
            }
        );
        //console.log("Query Executed");
    }
    catch (e) {throw e; //add this code for testing purposes, so the exception is not suppressed. not in the original.
    }
}
/*This function is used to execute the query and get the response*/
function ExecuteReader(query, db, success, fail) {
    try {
        console.log("Executing Select Query: " + query);
        //console.log(db);
        //console.log(db.transaction);
        db.transaction(
            function (transaction) {                
                transaction.executeSql(query, [], success, fail);                
            }
        );
    }
    catch (e) {throw e; //add this code for testing purposes, so the exception is not suppressed. not in the original.
    }
}


/*This function is used to execute the query and get the response fail and success in single function*/
/*
function ExecuteReaderWithSingleCallback(query, db, callback) {
    try {
        console.log("Executing Query: " + query);
        db.transaction(
            function (transaction) {
                transaction.executeSql(query, [], callback, callback);
            }
        );
    }
    catch (e) {
    }
}
*/

function ExecuteReaderWithSingleCallback(query, db, callback) {
    try {
        console.log("Executing Query: " + query);
        if (IsNullOrEmpty(query)) {
            callback(null, null);
            return;
        }

        db.transaction(
            function (transaction) {
                transaction.executeSql(query, [], callback, function (transaction, error) {
                    //debugger;
                    //alert("SQL Error: " + error.message);
                    console.log("SQL Error" + error.message);
                    callback(transaction, error);
                });
            }
        );
    }
    catch (e) {throw e; //add this code for testing purposes, so the exception is not suppressed. not in the original.
    }
}


/*This function is used to execute query Synchronously*/
function ExecuteSyncQuery(query, db) {
    console.log("Executing Sync Query: " + query);    
    var resultPar;
    var resultErr;
    db.transaction(
               function (transaction) {
                   transaction.executeSql(query,
                   function (tt, result) {
                       console.log("Success");
                       //console.log("Success" + tt);
                       //console.log("Success" + result);
                       resultPar = result;
                   },
                   function (tt, result) {
                       console.log("Fail");
                      // console.log("Fail" + tt);
                      // console.log("Fail" + result); 
                       resultErr = result;
                   }
                   );
    });

    //console.log(resultPar);
    //console.log(resultErr);
    //console.log("Completed Sync Query");
}

//callback format example: function (bRet) { alert(bRet); }; bRet = true if all quries runs fine.
//Do not use this one for time sensitive situation. Somehow it will cause weird problem.
function ExecuteMultipleQuery(queryList, db, callback) {
    if (!queryList || queryList.length <= 0) {
        callback(true);
        return;
    }

    db.transaction(function (transaction) {
        var bRet = true;
        for (var m = 0; m < queryList.length; m++) {
            try {
                console.log("Executing Query: " + queryList[m]);
                if (m < (queryList.length - 1))
                    transaction.executeSql(queryList[m], [], function (tt, result) { console.log("Success"); }, function (tt, result) { console.log("Fail"); bRet = false; });
                else
                    transaction.executeSql(queryList[m], [],
                        function (tt, result) {
                            console.log("Success");
                            callback(bRet);
                        },
                        function (tt, result) {
                            console.log("Fail");
                            bRet = false;
                            callback(bRet);
                        });
            }
            catch (e) {throw e; //add this code for testing purposes, so the exception is not suppressed. not in the original.
                console.log("Failed: query = " + queryList[m]);
                bRet = false;
            }
        }

    });
}

//Helper function
function IsNumber(n) {
    return !isNaN(parseFloat(n)) && isFinite(n);
}

//If only want to check undefied or null, simply call if(var).
function IsNullOrEmpty(val) {
    return (val === undefined || val == null || val.length <= 0) ? true : false;
}